package XML;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Deom4jModXml {
    public void Dmod() throws Exception {
        // 获取一个Document对象
        File url = new File("D:\\GitHOME\\information\\text.xml");
        SAXReader saxReader = new SAXReader();

        Document doc = null;

        {
            try {
                doc = saxReader.read(url);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }


        // 获取id为1的节点下的name元素

        Node name = doc.selectSingleNode("/spots/spot[@id = 'i']/name[i]");

        name.setText("这里是修改的id为1的节点下的name元素值");


        // 注意：XML文件是被加载到内存中 修改也是在内存中 ==》因此需要将内存中的数据同步到磁盘中

        XMLWriter writer = null;//将内存数据关联给一个字符输出流

        {
            try {
                writer = new XMLWriter(new FileWriter(url));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        writer.write(doc);

        writer.close();
    }
}
